import Vue from 'vue'
import Router from 'vue-router'
import { getUrlParamByKey } from 'vue-xiaobu-utils'

Vue.use(Router)

// 要求页面顺序按照交易类型排列
let pageList = [
  'WalletRechargeBill',
  'WalletReturnBill',
  'BusConsumeBill',
  'BusConsumeReturnBill',
  'MallConsumeBill',
  'MallConsumeReturnBill',
  'ICCardConsumeBill',
  'ICCardConsumeReturnBill'
]
let pageListLength = pageList.length
let routes = []

pageList.forEach((pageName, i) => {
  const myComponent = () =>
    import(/* webpackChunkName: "routebill/" */ '../page/' + pageName + '.vue')
  let route = {
    path: '/' + pageName,
    name: pageName,
    component: myComponent
  }
  routes.push(route)
})

const router = new Router({
  routes: routes
})

// 全局路由守护
router.beforeEach((to, from, next) => {
  // 根据url上带入的交易类型,指向不同的路由
  let path
  let tradeType = getUrlParamByKey('tradetype')
  tradeType = tradeType ? parseInt(tradeType) : 1
  if (tradeType > 0 && tradeType <= pageListLength) {
    path = routes[tradeType - 1].path
  }
  if (path !== to.path) {
    // next({ path: path })
    router.replace({ path: path })
  }
  next()
})

export default router
